import { mutation, query } from './_generated/server'
import { v } from 'convex/values'

const images = [
    "placeholders/1.svg",
    "placeholders/2.svg",
    "placeholders/3.svg",
    "placeholders/4.svg",
    "placeholders/5.svg",
    "placeholders/6.svg",
    "placeholders/7.svg",
    "placeholders/8.svg",
    "placeholders/9.svg",
    "placeholders/10.svg"
];
export const create = mutation({
    args: {
        orgId: v.string(),
        title: v.string()
    },
    handler: async (ctx, args) => {
        const identity = await ctx.auth.getUserIdentity();
        if (!identity) {
            throw new Error("Unauthorized");
        }
        const randomImage = images[Math.floor(Math.random() * images.length)];
        console.log(randomImage, "TEST");
        const board = await ctx.db.insert("boards", {
            title: args.title,
            orgId: args.orgId,
            authorId: identity.subject,
            authorName: identity.name || 'Anonymous',
            imageUrl: randomImage,
        });
    }


}
)

// 定义一个删除操作，用于从数据库中移除指定的记录
export const remove = mutation({
    // 配置删除操作的参数
    args: {
        id: v.id("boards"), // 指定参数id为boards类型的唯一标识符
    },
    // 定义删除操作的处理函数
    handler: async (ctx, args) => {
        // 获取当前用户的认证信息
        const identity = await ctx.auth.getUserIdentity();

        // 如果用户未认证，则抛出Unauthorized错误
        if (!identity) {
            throw new Error("Unauthorized");
        }

        // 从用户认证信息中提取出用户ID
        const userId = identity.subject;

        // 查询当前用户是否已将要删除的看板设为收藏
        const existingFavorite = await ctx.db
            .query("userFavorites")
            .withIndex("by_user_board", (q) =>
                q.eq("userId", userId).eq("boardId", args.id)
            )
            .unique();

        // 如果存在收藏记录，则删除该收藏记录
        if (existingFavorite) {
            await ctx.db.delete(existingFavorite._id);
        }

        // 删除指定的看板记录
        await ctx.db.delete(args.id);
    },
});
export const update = mutation({
    args: { id: v.id("boards"), title: v.string() }, // 定义参数，id 是一个 "boards" 类型的 ID，title 是一个字符串
    handler: async (ctx, args) => {
        const identity = await ctx.auth.getUserIdentity(); // 获取用户身份

        if (!identity) {
            throw new Error("Unauthorized"); // 如果没有身份，抛出未授权错误
        }

        const title = args.title.trim(); // 去除标题两端的空白字符

        if (!title) {
            throw new Error("Title is required"); // 如果标题为空，抛出错误
        }

        if (title.length > 60) {
            throw new Error("Title cannot be longer than 60 characters"); // 如果标题长度超过60个字符，抛出错误
        }

        const board = await ctx.db.patch(args.id, {
            title: args.title
        }); // 更新数据库中对应 ID 的条目，设置新的标题
        return board;
    },
});

export const favorite = mutation({
    args: { id: v.id("boards"), orgId: v.string() },
    handler: async (ctx, args) => {
        const identity = await ctx.auth.getUserIdentity();

        if (!identity) {
            throw new Error("Unauthorized");
        }

        const board = await ctx.db.get(args.id);

        if (!board) {
            throw new Error("Board not found");
        }

        const userId = identity.subject;

        const existingfavorite = await ctx.db
            .query("userFavorites")
            .withIndex("by_user_board", (q) =>
                q.eq("userId", userId).eq("boardId", board._id)
            )
            .unique();

        if (existingfavorite) {
            throw new Error("Board already favorited");
        }

        await ctx.db.insert("userFavorites", {
            orgId: args.orgId,
            userId: userId,
            boardId: board._id,
        });

        return board;
    },
});

export const unfavorite = mutation({
    args: { id: v.id("boards") },
    handler: async (ctx, args) => {
        const identity = await ctx.auth.getUserIdentity();

        if (!identity) {
            throw new Error("Unauthorized");
        }

        const board = await ctx.db.get(args.id);

        if (!board) {
            throw new Error("Board not found");
        }

        const userId = identity.subject;

        const existingfavorite = await ctx.db
            .query("userFavorites")
            .withIndex("by_user_board", (q) =>
                q.eq("userId", userId).eq("boardId", board._id)
            )
            .unique();

        if (!existingfavorite) {
            throw new Error("favorited board not found");
        }

        await ctx.db.delete(existingfavorite._id);

        return board;
    },
});


export const get = query({
    args: { id: v.id("boards") },
    handler: async (ctx, args) => {
        const board = await ctx.db.get(args.id);

        if (!board) {
            throw new Error("Board not found");
        }

        return board;
    },
});